package com.zy.mobile.message.push.netty.heartbeat;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import ch.qos.logback.classic.Logger;

import com.zy.mobile.message.push.netty.chapter8.protobuf.SubscribeReqProto;
import com.zy.mobile.message.push.netty.chapter8.protobuf.SubscribeRespProto;
import com.zy.mobile.message.push.netty.chapter8.protobuf.SubscribeReqProto.SubscribeReq;
import com.zy.mobile.message.push.netty.heartbeat.protobuf.MessageProto;
import com.zy.mobile.message.push.netty.heartbeat.util.ChannelHandlerContextMap;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class HeartBeatServerHandler extends ChannelHandlerAdapter{
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
//		ChannelHandlerContextMap.put(ctx.channel().id().toString(),ctx);
		super.channelActive(ctx);
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// TODO Auto-generated method stub
		MessageProto.Message message = (MessageProto.Message) msg;		
//		System.out.println("Service accept client message : ["+message.toString()+"]");
		
		Integer courierId = message.getCourierId();
		ConcurrentHashMap<Integer,ChannelHandlerContext> map = ChannelHandlerContextMap.getMap();
			
		if(!map.containsKey(courierId)){
			ChannelHandlerContextMap.put(courierId, ctx);
		}else{
			ChannelHandlerContext ctxFromMap = ChannelHandlerContextMap.get(courierId);
			if(ctxFromMap.channel().id().toString().equalsIgnoreCase(ctx.channel().id().toString())){
				System.out.println("ok channel id is "+ctx.channel().id().toString());
			}else{
				ChannelHandlerContextMap.put(courierId, ctx);
			}
		}
		
		ctx.writeAndFlush(buildMesage());
	}
	
	public MessageProto.Message buildMesage(){
		MessageProto.Message.Builder builder = MessageProto.Message.newBuilder();
		builder.setType(4);
		builder.setTimeStamp(new Date().getTime());
		return builder.build();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();
		ctx.close();
	}
}
